﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo;
using ConfExpert.Properties;
using ConfExpert.Utility;

using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Sistem
{
    public partial class Repository : XForm
    {
        string LookUpName, TableName = string.Empty;
        public Repository(string _TableName)
            : this()
        {
            TableName = _TableName;
            sccAna.PanelVisibility = SplitPanelVisibility.Panel2;
            this.Text = TableName;
        }

        public Repository()
        {
            InitializeComponent();

            //select 'TAM.'+TABLE_NAME+'TableAdapter = new '+TABLE_NAME+'TableAdapter();' from LookUp where Tip = 'T' order by TABLE_NAME 

            //StyleFormatCondition cn;
            //cn = new StyleFormatCondition(FormatConditionEnum.Equal, gridView1.Columns["Deleted"], null, 1);
            //cn.ApplyToRow = true;
            //cn.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Strikeout);
            //cn.Appearance.ForeColor = SystemColors.ControlDark;
            //gridView1.FormatConditions.Add(cn);

        }


        private void Repository_Load(object sender, EventArgs e)
        {
            sccDetay.PanelVisibility = SplitPanelVisibility.Panel1;

            gvLookUp2.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gvLookUp2_RowStyle);
            //btnSeri.Click += new EventHandler(btnSeri_Click);
            //btnKaydet.Click += new EventHandler(btnKaydet_Click);
            //btnENUMform.Click += new EventHandler(btnENUM_Click);
            //btnENUMta.Click += new EventHandler(btnENUMta_Click);
            //btnENUMrp.Click += new EventHandler(btnENUMrp_Click);
            //btnMakeLookUps.Click += new EventHandler(btnMakeLookUps_Click);
            chkGoster.CheckedChanged += ChkGoster_CheckedChanged;

            
           
            gvLookUp.ShowingEditor += new System.ComponentModel.CancelEventHandler(gvLookUp_ShowingEditor);


            gvLookUp.Init("GetLookUp", WhoAmI);
            gvLookUp.MakeColumnInvisible("Tip", "DisplayMember", "ValueMember", "LastModified", "ModifiedOn", "Description");
            if (!ytk(17))
                gvLookUp.MakeColumnInvisible("isEditable");
            gvLookUp.FocusedRowChanged += gvLookUp_FocusedRowChanged;

            gvLookUp.ClearColumnEdit("LookUpId");
           
            gvLookUp.AddSummary();
            gvLookUp.MakeRowSelectable();
            gvLookUp.BestFitColumns();

            if (TableName != string.Empty)
                LookUpChanged(TableName);

            if (TableName == "Tela")
            {
                //gvLookUp2.MakeColumnInvisible("Scan");
                gvLookUp2.YanYanaGetirSoluna("Agirlik", "Art", "Col", "ColDesc");

                GridManager gm = GridManager.GetManager(gvLookUp2);
                gm.GridMenu.AddMenu("Bu artikelin hareketleri", Hareketler, Resources.StokHareketleri16x16);
                if (ytk(64))
                    gm.GridMenu.AddMenu("Kart birleştir", Birlestir);

                btnKaydet.Enabled = ytk(165); // K.DEPO + K.SATINALMA
            }
            
            btnKaydet.ItemClick += btnKaydet_ItemClick;
        }

        void gvLookUp_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle > -1)
            {
                if (ds.HasChanges())
                {
                    if (XtraMessageBox.Show("Değişen kayıtları saklamak ister misiniz?", "Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        btnKaydet.PerformClick();
                    else
                        ds.RejectChanges();
                }

                LookUpChanged(gvLookUp.GetFocusedDataRow()["TABLE_NAME"].ToStr());
            }
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvLookUp2.EndEditing();
            gvLookUp2.Update("", gvLookUp.GetFocusedDataRow()["TABLE_NAME"].ToStr());
            gvLookUp2.RefreshDataSource("GetTable", LookUpName);
            this.FormClosing += new FormClosingEventHandler(Repository_FormClosing);

            AppSession.MainForm.RefreshData();
        }

        private void Hareketler(object sender, EventArgs e)
        {
            int productId = gvLookUp2.GetFocusedDataRow()["ProductId"].ToInt();
            if (productId > 0)
                using (DepoStokHareketler rzv = new DepoStokHareketler(productId))
                {
                    rzv.ShowDialog();
                }
        }

        private void Birlestir(object sender, EventArgs e)
        {
            using (Depo.Tela.Duzelt d = new Depo.Tela.Duzelt())
            {
                d.ShowDialog();
                AppSession.MainForm.RefreshData();
            }
        }

        void gvLookUp_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = gvLookUp.FocusedColumn.FieldName == "LookUpId" ||
                gvLookUp.FocusedColumn.FieldName == "TABLE_NAME";
        }

        void Repository_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ds.HasChanges())
                if (XtraMessageBox.Show("Yaptığınız değişiklikleri kaydetmek ister misiniz?", "Critical Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    btnKaydet.PerformClick();
        }

        void btnENUMrp_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(ExecuteScalar("ENUMrp").ToString().Replace("|", Environment.NewLine));
        }

        void btnMakeLookUps_Click(object sender, EventArgs e)
        {
            ExecuteNonQuery("MakeLookUp");
        }

        void btnENUMta_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(ExecuteScalar("ENUMta").ToString().Replace("|", Environment.NewLine));
        }

        void btnENUM_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(ExecuteScalar("ENUMform").ToString().Replace("|", Environment.NewLine));
        }

        private void ChkGoster_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            /*
            if (bsLookUp2 != null)
                bsLookUp2.Filter = chkGoster.Checked ? "" : "isNull(Deleted, 0) = 0";
             */
        }

        private delegate void UpdateDataSourceHandler();

        void gvLookUp2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if ((sender as GridView).GetRowCellValue(e.RowHandle, "Deleted") != null)
                    if ((sender as GridView).GetRowCellValue(e.RowHandle, "Deleted") != DBNull.Value)
                        if ((bool)(sender as GridView).GetRowCellValue(e.RowHandle, "Deleted") == true)
                        {
                            e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Strikeout);
                            e.Appearance.ForeColor = Color.Gray; // SystemColors.ControlDark;
                        }
            }
        }

        void gvFeatures_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
                if (gvFeatures.GetRowCellValue(e.RowHandle, "isApplicable").ToString() == bool.TrueString)
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        private void LookUpChanged(string _LookUpName)
        {
            LookUpName = txtInfo.Caption = _LookUpName;
            gvLookUp.FocusedRowHandle = gvLookUp.LocateByValue("TABLE_NAME", _LookUpName);
            ExpandCollapse(sccDetay, LookUpName == "ProductCategory" ? AcKapa.Expand : AcKapa.Collapse);

            gvLookUp2.BeginSort();
            gvLookUp2.Init("GetTable", LookUpName);
            gvLookUp2.AddSummary();

            gvLookUp2.RowCellStyle -= gvLookUp2_RowCellStyle;
            gvLookUp2.RowCellStyle += gvLookUp2_RowCellStyle;

            gvLookUp2.ShowingEditor -= gvLookUp2_ShowingEditor;
            if (LookUpName == "Kalite")
                gvLookUp2.ShowingEditor += gvLookUp2_ShowingEditor;

            gvLookUp2.Columns[0].Caption = "#";
            gvLookUp2.Columns[0].ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
            gvLookUp2.Columns[0].AppearanceCell.BackColor = Color.LightYellow;
            gvLookUp2.MakeColumnsReadOnly(gvLookUp2.Columns[0].FieldName);

            gvLookUp2.AddAutoIncrementalPK(_LookUpName + "Id");            

            if (LookUpName == "ProductCategory")
            {
                ds.nStok.Merge(ExecuteDataTable("GetNebim", "Stok"));
                gvLookUp2.Columns["nStokId"].ColumnEdit = GetNebimRI(ds.nStok, "nStokID");
                gvLookUp2.MakeColumnInvisible("ApplicableFeatures");
            }
            else if (LookUpName == "Cari")
            {
                ds.nFirma.Merge(ExecuteDataTable("GetNebim", "Firma"));
                gvLookUp2.Columns["nFirmaId"].ColumnEdit = GetNebimRI(ds.nFirma, "nFirmaID");
            }
            else if (LookUpName == "Kalite")
            {
                gvLookUp2.Columns["Konstruksiyon"].ColumnEdit = GetIntellisensedRI(RepositoryManager.Kons); // GetIntellisensedRI(ExecDatatable("GetDistinctValues", "Konstruksiyon"));
                ((RepositoryItemGridLookUpEdit)gvLookUp2.Columns["Konstruksiyon"].ColumnEdit).ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
            }
            else if (LookUpName == "Hammadde")
            {
                gvLookUp2.MakeColumnInvisible("Yuzdesi");
                txtInfo.Caption = "Kumaş hammaddesi";
            }

            chkGoster.Visibility = gvLookUp2.Columns.Contains(gvLookUp2.Columns["Deleted"]) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;

            gvLookUp2.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            //gvEntities.Columns["Deleted"].ColumnEdit = new RepositoryItemCheckEdit();
            //((RepositoryItemCheckEdit)gvEntities.Columns["Deleted"].ColumnEdit).EditValueChanged += new EventHandler(Repository_EditValueChanged);
            gvLookUp2.BestFitColumns();
            gvLookUp2.EndSort();
        }

        void gvLookUp2_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = gvLookUp2.FocusedColumn.FieldName == "Name" &&
                gvLookUp2.GetFocusedRowCellValue("KaliteId").ToInt() > 0 &&
                gvLookUp2.GetFocusedRowCellValue("KaliteId").ToInt() <= 150;
        }

        void gvLookUp2_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "Art" || e.Column.FieldName == "Col" || e.Column.FieldName == "ColDesc")
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        private void btnSeri_Click(object sender, EventArgs e)
        {
            using (Seri series = new Seri())
                series.ShowDialog();
        }



    }
}